import paramiko
import time

# 远程服务器的配置信息
hostname = '172.16.91.154'
port = 22  # SSH端口，默认为22
username = 'root'
password = '1zsfg1th'

# 创建SSH对象
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

try:
    # 连接到远程服务器
    ssh.connect(hostname, port, username, password)


    def exec_command(command):
        stdin, stdout, stderr = ssh.exec_command(command)
        return stdout.read().decode('utf-8')


    def get_system_metrics():
        # 获取远程服务器的CPU使用率
        cpu_usage = exec_command("top -bn1 | grep 'Cpu(s)' | awk '{print $2 + $4}'")
        # 获取远程服务器的内存使用量
        memory_usage = exec_command("free -m | grep Mem | awk '{print $3/$2 * 100.0}'")
        # 获取远程服务器的磁盘使用量
        disk_usage = exec_command("df -h / | grep / | awk '{print $5}' | sed 's/%//g'")
        # 获取远程服务器的网络信息
        net_io = exec_command("sar -n DEV 1 1 | awk '{print $3, $4}'")
        net_io_parts = net_io.split()
        if len(net_io_parts) >= 2:
            net_sent, net_received = net_io_parts
        else:
            net_sent, net_received = 'N/A', 'N/A'
        # 获取远程服务器的系统运行时间和负载
        boot_time = exec_command("date -d @$(awk '/^\\[/ {print $2}' /proc/uptime)")
        loadavg = exec_command("uptime | sed 's/.*load average: //'")

        loadavg_parts = loadavg.split(',')
        if len(loadavg_parts) >= 3:
            load1, load5, load15 = loadavg_parts[:3]
        else:
            load1, load5, load15 = 'N/A', 'N/A', 'N/A'

        return {
            'CPU Usage': cpu_usage.strip(),
            'Memory Usage': memory_usage.strip(),
            'Disk Usage': disk_usage.strip(),
            'Network IO': {
                'Sent': net_sent.strip(),
                'Received': net_received.strip(),
            },
            'System Boot Time': boot_time.strip(),
            'System Load': {
                '1 min': load1.strip(),
                '5 min': load5.strip(),
                '15 min': load15.strip(),
            }
        }


    def monitor_system(interval=50):
        while True:
            metrics = get_system_metrics()
            print("System Metrics:", metrics)
            time.sleep(interval)


    if __name__ == "__main__":
        monitor_system()

except Exception as e:
    print(f"连接或执行命令失败: {e}")

finally:
    # 关闭SSH连接
    ssh.close()